package guzb.cnblogs.security.industrydemo.auth.restful;

import com.fasterxml.jackson.databind.ObjectMapper;
import guzb.cnblogs.security.industrydemo.util.JsonResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * MyUserPasswordAuthenticationResultHandler
 */
public class MyUserPasswordAuthenticationResultHandler implements AuthenticationSuccessHandler, AuthenticationFailureHandler {

    private ObjectMapper objectMapper;

    public MyUserPasswordAuthenticationResultHandler() {
        this.objectMapper = new ObjectMapper();
    }

    public MyUserPasswordAuthenticationResultHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        String responseBody = objectMapper.writeValueAsString(JsonResponse.err401("登录失败：" + exception.getMessage()));
        response.getWriter().write(responseBody);
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json; charset=utf-8");
        MyUsernamePasswordAuthenticationToken myAuthToken = (MyUsernamePasswordAuthenticationToken) authentication;
        String body = objectMapper.writeValueAsString(JsonResponse.ok(myAuthToken));
        response.getWriter().write(body);
    }
}
